﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;
using Hxsoft.AppV1.Module;

namespace Hxsoft.AppV1.WebUI
{
	public class CommentSpecialModule : ISpecialModuleParser
	{
		#region
		public static string ParseCommentList(SpecialPageInfo page, string template, List<Comments.CommentForClientList> list, bool? isShowHeader, bool? isShowMore, int? loadCount, string listTitle, string listUrl, string listTarget, string cssClass)
		{
			string content = template;
			Regex reg = new Regex(@"<headerTemplate>((?:.|\n|\r)*?)</headerTemplate>", RegexOptions.IgnoreCase);
			if (isShowHeader == false)
				content = reg.Replace(content, "");
			else
				content = reg.Replace(content, "$1");

			Regex regMore = new Regex(@"<moreTemplate>((?:.|\n|\r)*?)</moreTemplate>", RegexOptions.IgnoreCase);
			bool showMore = isShowMore.HasValue ? isShowMore.Value : loadCount.HasValue;
			if (showMore == false)
				content = regMore.Replace(content, "");
			else
				content = regMore.Replace(content, "$1");

			content = content.Replace("{ListTitle}", listTitle);
			content = content.Replace("{ListUrl}", listUrl);
			content = content.Replace("{ListTarget}", listTarget);
			content = content.Replace("{ListTargetAttribute}", string.IsNullOrEmpty(listTarget) ? "" : @" target=""" + listTarget + @"""");
			content = content.Replace("{CssClass}", string.IsNullOrEmpty(cssClass) ? "" : @" class=""" + cssClass + @"""");
			content = content.Replace("{AttachedClass}", string.IsNullOrEmpty(cssClass) ? "" : @" " + cssClass);
			content = content.Replace("{ModuleIndex}", page.ModuleCounter.ToString());

			Regex reg2 = new Regex("<itemTemplate>((?:.|\n|\r)*?)</itemTemplate>", RegexOptions.IgnoreCase);
			Match match2 = reg2.Match(content);
			if (match2 != Match.Empty)
			{
				string items = "";
				string itemTemplate = match2.Groups[1].Value;
				foreach (var data in list)
				{
					string item = itemTemplate.Replace("{ItemPostIp}", data.PostIp);
					item = item.Replace("{ItemDisplayPostIp}", "");
					item = item.Replace("{ItemPostTime}", data.PostTime.ToString());
					item = item.Replace("{ItemQuote}", data.Quote);
					item = item.Replace("{ItemContent}", data.Content);
					item = item.Replace("{ItemCommentId}", data.CommentId.ToString());

					items += item;
				}

				content = reg2.Replace(content, items);
			}

			return content;
		}

		public static string BuildCheckCodeTag(SpecialPageInfo page)
		{
			string html = @"<img class=""checkCode"" src=""" + ApplicationConfiguration.CheckCodeImageUrl + @""" align=""absmiddle"" /><a href=""javascript:void(0);"" onclick=""$('.checkCode').each(function(i, e){ e.src = '" + ApplicationConfiguration.CheckCodeImageUrl + @"?t=' + new Date().getTime(); });"">看不清</a>";
			page.RegisterHeadIncludeFile(ApplicationConfiguration.JQueryUrl, IncludeFileType.JS);
			return html;
		}

		public const string CommentForm = @"<div class=""commentForm"">
    <a name=""AddComment{ModuleIndex}""></a>
    <form method=""post"" action=""{PostCommentUrl}"">
        <input name=""FormId"" value=""{FormId}"" type=""hidden"" />
        <div class=""fieldBox"">
            <div class=""fieldTitle"">引用内容：</div>
            <div class=""fieldContent"">
                <input type=""hidden"" id=""Comment{ModuleIndex}QuoteId"" name=""QuoteId"" value=""{FormQuoteId}"" /><input type=""hidden"" id=""Comment{ModuleIndex}Quote"" name=""Quote"" value=""{FormQuote}"" />
                <div id=""Comment{ModuleIndex}QuoteDisplayBox"" class=""contentBox"">{QuoteHtml}</div>
            </div>
        </div>
        <div class=""fieldBox"">
            <div class=""fieldTitle"">评论内容：</div>
            <div class=""fieldContent""><textarea name=""Content"" rows=""8"">{FormContent}</textarea><span class=""red"">{FormContentMessage}</span></div>
        </div>
        <div class=""toolbar"">
            验证码：<input type=""text"" name=""CheckCode"" size=""6"" valu=""{FormCheckCode}"" /><span class=""red"">{FormCheckCodeMessage}</span>{CheckCode}
            <input id=""CbIsAnonymity"" type=""checkbox"" name=""Anonymity"" value=""true""/>匿名
            <input type=""submit"" value=""发表"" /><span class=""red"">{FormMessage}</span>
        </div>
    </form>
    </div>
    <script type=""text/javascript"">
    function Comment{ModuleIndex}_SetQuote(quoteId, ip, quote, content)
    {
        this.getQuote = {GetCommentQuoteScript};
        
        var CtrQuoteId = document.getElementById(""Comment{ModuleIndex}QuoteId"");
        var CtrQuote = document.getElementById(""Comment{ModuleIndex}Quote"");
        var CtrQuoteDisplayBox = document.getElementById(""Comment{ModuleIndex}QuoteDisplayBox"");
        
        var value = this.getQuote(ip, quote, content);
        CtrQuoteId.value = quoteId;
        CtrQuote.value = value;
        CtrQuoteDisplayBox.innerHTML = value;
    }
    if({FormIsPost})
        $(function(){ alert(""您的评论已经成功提交。"") });
    </script>";

		/// <summary>
		/// 解析评论表单。
		/// </summary>
		/// <returns></returns>
		public static string ParseCommentForm(SpecialPageInfo page, string template, string infoType, string infoId, int moduleIndex, bool validateFormId)
		{
			string content = null;

			// 获取评论模板
			Regex reg = new Regex(@"<commentFormTemplate>((?:.|\n|\r)*?)</commentFormTemplate>", RegexOptions.IgnoreCase);
			Match m = reg.Match(template);
			if (m != Match.Empty)
				content = m.Groups[1].Value;
			else
			{
				reg = new Regex(@"{CommentForm}", RegexOptions.IgnoreCase);
				m = reg.Match(template);
				if(m != Match.Empty)
					content = CommentForm;
				else
					return content;
			}

			HttpContext context = HttpContext.Current;
			// 处理提交数据
			string formMessage = null;
			string formCheckCodeMessage = null;
			string formContentMessage = null;

			int? formQuoteId = null;
			string formQuote = null;
			string formContent = null;
			string formCheckCode = null;
			bool formIsPost = false;

			// 验证表单ID
			bool isValidateFormId = true;
			if (validateFormId)
			{
				int? formId = IntExtensions.ParseOrNull(context.Request["FormId"]);
				if (formId != moduleIndex)
					isValidateFormId = false;
			}

			if (isValidateFormId && (context.Request.HttpMethod == "POST" || !(string.IsNullOrEmpty(formContent) && string.IsNullOrEmpty(formCheckCode))))
			{
				formQuoteId = IntExtensions.ParseOrNull(context.Request["QuoteId"]);
				formQuote = context.Request["Quote"];
				formContent = context.Request["Content"];
				formCheckCode = context.Request["CheckCode"];

				Comment formComment = new Comment();
				formComment.QuoteId = formQuoteId;
				formComment.Quote = formQuote;
				formComment.Content = formContent;

				// 表单验证
				bool formValidated = true;
				if (!Hxsoft.Web.UI.WebControls.CheckCode.Validate(formCheckCode))
				{
					formValidated = false;
					formCheckCodeMessage = "输入了错误的验证码";
				}
				if (string.IsNullOrEmpty(formContent) || string.IsNullOrEmpty(formContent.Trim()))
				{
					formValidated = false;
					formContentMessage = "请输入评论内容";
				}

				formComment.InfoType = infoType;
				formComment.InfoId = infoId;

				if (formValidated)
				{
					if (Comments.GetPostRight(formComment))
					{
						formComment.PostIp = context.Request.UserHostAddress;
						formComment.SiteId = Sites.CurrentSiteId;
						Comments.Post(formComment);

						formQuoteId = null;
						formQuote = null;
						formContent = null;
						formCheckCode = null;
						formQuote = null;
						formIsPost = true;
					}
					else
						formMessage = "您没有发布评论的权限。";
				}
			}

			// 表单变量
			content = content.Replace("{GetCommentQuoteScript}", Comments.GetClientGetCommentQuoteScript());
			content = content.Replace("{FormQuoteId}", formQuoteId.ToString());
			content = content.Replace("{FormQuote}", HttpUtility.HtmlEncode(formQuote));
			content = content.Replace("{FormContent}", HttpUtility.HtmlEncode(formContent));
			content = content.Replace("{FormCheckCode}", HttpUtility.HtmlEncode(formCheckCode));
			content = content.Replace("{QuoteHtml}", formQuote);

			content = content.Replace("{FormMessage}", formMessage);
			content = content.Replace("{FormCheckCodeMessage}", formCheckCodeMessage);
			content = content.Replace("{FormContentMessage}", formContentMessage);
			content = content.Replace("{FormIsPost}", formIsPost.ToString().ToLower());

			content = content.Replace("{CheckCode}", BuildCheckCodeTag(page));
			content = content.Replace("{PostCommentUrl}", "");
			content = content.Replace("{ModuleIndex}", moduleIndex.ToString());
			content = content.Replace("{FormId}", moduleIndex.ToString());

			page.RegisterHeadIncludeFile(ApplicationConfiguration.JQueryUrl, IncludeFileType.JS);
			return reg.Replace(template, content);
		}
		#endregion




		public string BuildListUrl(string specialCode, string pageCode, string moduleCode, int? pageIndex)
		{
			return GenericUrlManager.BuildSpecialModuleListUrl(specialCode, pageCode, moduleCode, pageIndex);
		}

		public string BuildContentUrl(string specialCode, string pageCode, string moduleCode, int infoId)
		{
			return GenericUrlManager.BuildSpecialModuleContentUrl(specialCode, pageCode, moduleCode, infoId.ToString());
		}

		public string ParsePart(SpecialTemplateConfiguration templateConfiguration, SpecialModule module, SpecialPageConfiguration configuration, Special specialInfo, SpecialPage pageInfo, ref SpecialPageInfo page, bool isPreview)
		{
			string content = "";
			if (configuration == null) return content;
			if (module == null || module.ModuleId != configuration.ModuleId) return content;

			CommentContentConfiguration con1 = module.ContentConfigurationObject as CommentContentConfiguration;
			if (con1 == null) con1 = new CommentContentConfiguration();

			CommentPageConfiguration con = configuration as CommentPageConfiguration;
			if (con == null) con = new CommentPageConfiguration();
			if (string.IsNullOrEmpty(con.ListTarget)) con.ListTarget = "_blank";
			SpecialContentTemplate contentTemplate = templateConfiguration.GetBlockTemplate(module.ModuleType, con.ListType);
			if (contentTemplate == null) return content;

			CommentContentConfiguration moduleCon = module.ContentConfigurationObject as CommentContentConfiguration;
			string contentPageCode = moduleCon == null ? "" : moduleCon.ContentPage;

			content = contentTemplate.GetTemplate(con.Parameters);
			content = ParseCommentForm(page, content, con1.InfoType, con1.InfoId, page.ModuleCounter, true);

			List<Comments.CommentForClientList> list = null;

			if (isPreview)	// 读预览数据。
			{
				string json = templateConfiguration.GetBlockPreviewData(module.ModuleType, contentTemplate.ViewType);
				if (!string.IsNullOrEmpty(json)) list = Serialization.DeserializeJson<List<Comments.CommentForClientList>>(json);
			}

			if (list == null) list = Comments.GetList(specialInfo.SiteId, con1.InfoType, con1.InfoId, con.LoadCount);

			content = ParseCommentList(page, content, list, con.ShowHeader, con.ShowMore, con.LoadCount, module.ModuleName, BuildListUrl(specialInfo.SpecialCode, contentPageCode, module.ModuleCode, null), con.ListTarget, con.CssClass);

			if (contentTemplate.HeadIncludeFiles != null)	// 头部包含文件
			{
				foreach (var file in contentTemplate.HeadIncludeFiles)
					page.RegisterHeadIncludeFile(file.Key, file.Value);
			}

			if (isPreview)		// 加载预览样式
			{
				page.TemplateCssUrls = templateConfiguration.TemplateCssUrls;
				if (page.TemplateCssUrls != null)
				{
					for (int i = 0; i < page.TemplateCssUrls.Length; i++)
					{
						var url = page.TemplateCssUrls[i];
						if (!string.IsNullOrEmpty(url))
							page.TemplateCssUrls[i] = url.Replace(SpecialPages.TemplateConst_TemplateRootUrl, SpecialPages.TemplateRootUrl);
					}
				}
			}

			// 替换其它模板变量
			content = GenericHelper.ReplaceSpecialTemplateParameters(content, contentTemplate.OtherParameters, con.Parameters);

			return content;
		}

		public string ParseContent(SpecialTemplateConfiguration templateConfiguration, SpecialModule module, Special specialInfo, SpecialPage pageInfo, ref SpecialPageInfo page, bool isPreview)
		{
			string content = "";
			if (module == null) return content;

			if (isPreview) return content;		// 没有预览内容。

			HttpContext context = HttpContext.Current;

			int infoId = int.Parse(context.Request.QueryString[GenericUrlManager.Special_Query_ModuleInfoIdField]);

			CommentContentConfiguration con = module.ContentConfigurationObject as CommentContentConfiguration;
			if (con == null) con = new CommentContentConfiguration();
			string contentPageCode = con.ContentPage;

			// 当前位置
			page.Locations.Add(new NavigationItem() { Text = module.ModuleName, Url = BuildListUrl(specialInfo.SpecialCode, contentPageCode, module.ModuleCode, null) });
			page.Locations.Add(new NavigationItem() { Text = Res.Content, Url = BuildContentUrl(specialInfo.SpecialCode, contentPageCode, module.ModuleCode, infoId) });

			return "";
		}

		public string ParseList(SpecialTemplateConfiguration templateConfiguration, SpecialModule module, Special specialInfo, SpecialPage pageInfo, ref SpecialPageInfo page, bool isPreview)
		{
			string content = "";
			if (module == null) return content;

			CommentContentConfiguration con = module.ContentConfigurationObject as CommentContentConfiguration;
			if (con == null) con = new CommentContentConfiguration();
			SpecialContentTemplate contentTemplate = templateConfiguration.GetContentTemplate(module.ModuleType, CommentContentViewType.List.ToString(), con.ListType);
			if (contentTemplate == null) return content;

			string contentPageCode = con.ContentPage;
			int currentPage = 1;
			PaginationInfo<List<Comments.CommentForClientList>> paginationInfo = null;

			content = contentTemplate.GetTemplate(con.ListParameters);
			content = ParseCommentForm(page, content, con.InfoType, con.InfoId, page.ModuleCounter, false);

			if (isPreview)	// 读预览数据。
			{
				string json = templateConfiguration.GetContentPreviewData(module.ModuleType, CommentContentViewType.List.ToString(), contentTemplate.ViewType);
				if (!string.IsNullOrEmpty(json)) paginationInfo = Serialization.DeserializeJson<PaginationInfo<List<Comments.CommentForClientList>>>(json);
			}
			else
			{
				HttpContext context = HttpContext.Current;
				currentPage = IntExtensions.ParseOrDefault(context.Request.QueryString[GenericUrlManager.Special_Query_ModulePageField], 1);
			}

			if (paginationInfo == null) paginationInfo = Comments.GetPaginationList(specialInfo.SiteId, con.InfoType, con.InfoId, con.ListPageSize.GetValueOrDefault(20), currentPage);
			if (paginationInfo == null) return content;

			content = ParseCommentList(page, content, paginationInfo.Records, true, true, null, module.ModuleName, BuildListUrl(specialInfo.SpecialCode, contentPageCode, module.ModuleCode, null), null, con.ListCssClass);

			content = content.Replace("{Pager}", GenericHelper.BuildSpecialListPager(paginationInfo, GenericUrlManager.BuildSpecialModuleListUrlPattern(specialInfo.SpecialCode, contentPageCode, module.ModuleCode)));

			if (contentTemplate.HeadIncludeFiles != null)	// 头部包含文件
			{
				foreach (var file in contentTemplate.HeadIncludeFiles)
					page.RegisterHeadIncludeFile(file.Key, file.Value);
			}

			if (isPreview)		// 加载预览样式
			{
				page.TemplateCssUrls = templateConfiguration.TemplateCssUrls;
				if (page.TemplateCssUrls != null)
				{
					for (int i = 0; i < page.TemplateCssUrls.Length; i++)
					{
						var url = page.TemplateCssUrls[i];
						if (!string.IsNullOrEmpty(url))
							page.TemplateCssUrls[i] = url.Replace(SpecialPages.TemplateConst_TemplateRootUrl, SpecialPages.TemplateRootUrl);
					}
				}
			}

			// 替换其它模板变量
			content = GenericHelper.ReplaceSpecialTemplateParameters(content, contentTemplate.OtherParameters, con.ListParameters);

			// 当前位置
			page.Locations.Add(new NavigationItem() { Text = module.ModuleName, Url = BuildListUrl(specialInfo.SpecialCode, contentPageCode, module.ModuleCode, null) });
			page.Title += "_" + module.ModuleName + Page.TitleSectionSeparator + string.Format(Res.TitlePaging, currentPage) + Hxsoft.AppV1.Page.TitleSuffix;	// 更新页面标题
			page.MetaKeywords += (string.IsNullOrEmpty(page.MetaKeywords) ? "" : ",") + module.ModuleName;

			return content;
		}

		#region ISpecialModuleParser 成员

		string ISpecialModuleParser.ParsePreviewPart(SpecialTemplateConfiguration templateConfiguration, SpecialModule module, SpecialPageConfiguration configuration, Special specialInfo, SpecialPage pageInfo, ref SpecialPageInfo page)
		{
			return ParsePart(templateConfiguration, module, configuration, specialInfo, pageInfo, ref page, true);
		}

		string ISpecialModuleParser.ParsePreviewContent(SpecialTemplateConfiguration templateConfiguration, SpecialModule module, Special specialInfo, SpecialPage pageInfo, ref SpecialPageInfo page, string moduleView)
		{
			if (moduleView == "Content")
				return ParseContent(templateConfiguration, module, specialInfo, pageInfo, ref page, true);
			else
				return ParseList(templateConfiguration, module, specialInfo, pageInfo, ref page, true);
		}


		string ISpecialModuleParser.ParsePart(SpecialTemplateConfiguration templateConfiguration, SpecialModule module, SpecialPageConfiguration configuration, Special specialInfo, SpecialPage pageInfo, ref SpecialPageInfo page)
		{
			return ParsePart(templateConfiguration, module, configuration, specialInfo, pageInfo, ref page, false);
		}

		string ISpecialModuleParser.ParseContent(SpecialTemplateConfiguration templateConfiguration, SpecialModule module, Special specialInfo, SpecialPage pageInfo, ref SpecialPageInfo page)
		{
			HttpContext context = HttpContext.Current;
			string view = context.Request.QueryString[GenericUrlManager.Special_Query_ModuleViewField];
			if (view == "Content")
				return ParseContent(templateConfiguration, module, specialInfo, pageInfo, ref page, false);
			else
				return ParseList(templateConfiguration, module, specialInfo, pageInfo, ref page, false);
		}

		#endregion
	}
}